#include "baseband.h"
#include "ts_peripheral.h"
#include "simple_uart.h"


static uint8_t channel;
static uint8_t scan_interval = 2;
static uint8_t ble_rx_data[37];

/// scan req data
//static uint8_t conn_req[39] = {0xC5, 0x22, 0x00, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x2F, 0x53, 0x65, 0x50, 0xD5, 0x6E, 0x93, 0x06, 0x06, 0x00, 0x18, 0x00, 0x00, 0x00, 0x48, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x48};
static uint8_t conn_req[39] = {0xC5, 0x22, 0x00, 0x01,0x02,0x03,0x04,0x05,0x06, 0x43, 0xD1, 0x68, 0x48, 0x5D, 0xD0, 0x2F, 0x53, 0x65, 0x50, 0xD5, 0x6E, 0x93, 0x06, 0x06, 0x00, 0x18, 0x00, 0x00, 0x00, 0x48, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x48};
static void scan_generic_onStart(void);
static void scan_generic_onWakeup(void);
static void scan_generic_onTxStarted(void);
static void scan_generic_onRxAA(void);
static void scan_generic_onRxPDU(void);
static void scan_generic_onSleep(void);
	
static const bb_fsm_t scan_generic_fsm = {
    0,
    scan_generic_onStart,
    scan_generic_onWakeup,
    scan_generic_onRxAA,
    scan_generic_onRxPDU,
    scan_generic_onTxStarted,
    scan_generic_onSleep,
		0
};

void bb_scanGenericStart( void )
{
		//bb_setConnState( ADV_STATE );
    bb_fsm = &scan_generic_fsm;
    bb_fsm->onStart();
}

static void scan_generic_onStart(void)
{
	 /*set channel*/
		bb_setConnRole(SCAN_STATE);
		channel = 38;
		periph_radio_ch_set(channel);
		channel++; 
		
}

static void scan_generic_onWakeup(void)
{
	if((bb_getConnRole() != M_CONN_REQ)){
		NRF_TIMER0->CC[3]=(NRF_TIMER0->CC[1] +150)%65536;
		NRF_TIMER0->CC[0]=(NRF_TIMER0->CC[1] +(scan_interval*1250))%65536;
		//NRF_TIMER0->CC[2]=(NRF_TIMER0->CC[1] +(scan_interval*1250) - 500)%65536; //- (adv_interval*500);
	}else{
		bb_mconnStart((uint8_t*)&conn_req[0], conn_req[1] + 3, NRF_TIMER0->CC[0]);
		
	}
}


static void scan_generic_onTxStarted(void)
{
	periph_radio_packet_ptr_set(&conn_req[0]);
}

static void scan_generic_onRxAA(void)
{
	uint8_t pdu_type = ble_rx_data[0] & 0x0F;
        switch (pdu_type) {

				case BB_PDU_TYPE_ADV_IND:
						if(ble_rx_data[3] == 0x43){
						/*	periph_radio_shorts_set(	RADIO_SHORTS_END_DISABLE_Msk  
																| RADIO_SHORTS_DISABLED_TXEN_Msk
																| RADIO_SHORTS_READY_START_Msk
																);*/
							bb_setConnRole(M_CONN_REQ);
							nrf_gpio_pin_toggle(12);
						}
					default:
							nrf_gpio_pin_toggle(13);
						break;
        }        
}

static void scan_generic_onRxPDU()
{

}


static void scan_generic_onSleep(void)
{
	periph_radio_packet_ptr_set(&ble_rx_data[0]);
	//radio_setMode(RADIO_MODE_ADV_TX);
}